package com.example.rbac.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.rbac.exception.CustomException;
import com.example.rbac.mapper.PermissionMapper;
import com.example.rbac.mapper.RolePermissionMapper;
import com.example.rbac.model.Permission;
import com.example.rbac.model.RolePermission;
import com.example.rbac.service.PermissionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    // 用于存储接口权限映射，键为请求方法+请求路径，值为权限标识
    private Map<String, String> apiPermissionMap = new ConcurrentHashMap<>();
    
    @Override
    public List<Permission> getAllPermissions() {
        return permissionMapper.selectList(null);
    }
    
    @Override
    public List<Permission> getPermissionsByRoleId(Long roleId) {
        return permissionMapper.selectPermissionsByRoleId(roleId);
    }
    
    @Override
    @Transactional
    public boolean assignPermissionsToRole(Long roleId, List<Long> permissionIds) {
        // 先删除角色原有的权限关联
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        rolePermissionMapper.delete(queryWrapper);
        
        // 添加新的权限关联
        for (Long permissionId : permissionIds) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissionMapper.insert(rolePermission);
        }
        
        return true;
    }
    
    @Override
    public void initPermissions() {
        // 清空现有的权限映射
        apiPermissionMap.clear();
        
        // 查询所有权限
        List<Permission> permissions = permissionMapper.selectAllPermissions();
        
        // 构建接口权限映射
        for (Permission permission : permissions) {
            if (permission.getUrl() != null && permission.getMethod() != null) {
                String key = permission.getMethod().toUpperCase() + ":" + permission.getUrl();
                apiPermissionMap.put(key, permission.getPermissionKey());
            }
        }
        
        System.out.println("权限初始化完成，共加载" + apiPermissionMap.size() + "个接口权限");
    }
    
    @Override
    public Map<String, String> getApiPermissionMap() {
        return apiPermissionMap;
    }
}